package com.briup.jdbc;

import org.junit.Test;

import java.sql.*;

/**
 * DQL语句使用，需要处理结果集
 */
public class Test5 {
    public static final String driver= "com.mysql.cj.jdbc.Driver";
    public static final String url= "jdbc:mysql:///db01";
    public static final String username= "root";
    public static final String password= "rootroot";

    @Test
    public void dqlSelect(){
        Connection connection = null;
        Statement statement = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url,username,password);
            // 创建语句对象
            statement = connection.createStatement();
            // 准备sql语句
            String sql = "select * from t_user";
            // 执行查询语句
            ResultSet resultSet = statement.executeQuery(sql);
            // 循环迭代
            while (resultSet.next()){
                // 每次循环为一行，需要取出每一列的数据
                int id = resultSet.getInt(1);
                String name = resultSet.getString("name");
                int age = resultSet.getInt("age");
                System.out.println("id = " + id);
                System.out.println("name = " + name);
                System.out.println("age = " + age);
            }

            System.out.println("查询成功");
            // 关闭资源
            resultSet.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {

            if(statement != null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if(connection != null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
